import React, { useState, useRef, useEffect } from 'react';
import { message, Button, Modal, Divider,Space } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { queryAlarmRules, addAlarmRules, updateAlarmRules, removeAlarmRules ,batchRemoveRules} from '@/services/alarmRules';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';


import { queryDeviceAttrList } from '@/services/deviceattr';
const { confirm } = Modal;
import styles from '@/global.less';
import { Link,useModel,useAccess, Access } from 'umi';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addAlarmRules(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateAlarmRules(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const remove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removeAlarmRules(fields);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }

};


const AlarmRules: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [EnumAlarmType, setEnumAlarmType] = useState({});
  const [dicAlarmType, setDicAlarmType] = useState([]);

  const [EnumAlarmLevel, setEnumAlarmLevel] = useState({});
  const [dicAlarmLevel, setDicAlarmLevel] = useState([]);

  const columns: ProColumns[] = [
    {
      title: '规则id',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '规则名称',
      dataIndex: 'alarmName',
      render: (text, record) => (
        <Space size="middle">
           <Link to={{pathname:`/alarm/rules/${record.id}`,state:{ruleInfo:record}}} > {text}</Link>
        </Space>
      ),
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName'
    },
    {
      title: '变量名称',
      dataIndex: 'browseName',
      search: false,
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum: EnumAlarmLevel,
     
    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
      valueEnum: EnumAlarmType,
    
    },
    {
      title: '最大值',
      dataIndex: 'maxValue',
      search: false,
    },
    {
      title: '最小值',
      dataIndex: 'minValue',
      search: false,
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      search: false,
      valueEnum: {
        0: { text: "未启用" },
        1: { text: "已启用" }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
       <>
         <Access accessible={access.canUpdate} fallback={null}>
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
           <Divider type="vertical" />
        </Access>
          <Access accessible={access.canDelete} fallback={null}>
          <a
            onClick={async () => {
              confirm({
                title: '您确定要删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await remove(record);
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
          >
            删除
          </a>
          </Access>
        </>
      ),
    },
  ];


  const getAttrList = async (deviceId,type=0) => {
    return await   queryDeviceAttrList({deviceId,type});
   } 

  useEffect(() => {
    const setSelectData = async () => {
    
      if (dicts) {
        setDicAlarmLevel(dicts["8"]);
        setDicAlarmType(dicts["6"]);
        setEnumAlarmType(dicts["6Enum"]);
        setEnumAlarmLevel(dicts["8Enum"]);
      }
      
    
    };
    setSelectData();
  }, []);
  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
//批量删除
const batchRemove = async () => {

  const hide = message.loading('正在删除');
  try {
    await batchRemoveRules({ ids: selectedRowKeys.join(',')});
    setSelectedRowKeys([]);
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};
  return (
    <>
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Access accessible={access.canUpdate} fallback={null}>
            <Button icon={<PlusOutlined />}  className={styles.addBtn}   onClick={() => handleModalVisible(true)}>
              新增
            </Button>
          </Access>
        ]}
        options={false}
        request={(params) => queryAlarmRules(params)}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 20,
        }}

        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}

   
        tableAlertOptionRender={(selected) => {
          return (
            <Space size={16}>
             
                 <a  onClick={() => {
                  confirm({
                    title: '您确定要批量删除吗?',
                    icon: <ExclamationCircleOutlined />,
                    async onOk() {
                      await batchRemove();
                      actionRef.current?.reload();
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }} >批量删除</a>
            </Space>
          );
        }}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
      />
     {dicAlarmType&&dicAlarmType.length>0? <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          console.log(success)
          if (success) {
            handleModalVisible(false);
            setFormValues({});
        
            //if (actionRef.current) {
              actionRef?.current?.reload();
           // }
          }
        }}
        onCancel={() => { handleModalVisible(false); setFormValues({}) }}
        modalVisible={createModalVisible}
        typelist={dicAlarmType}
        levellist={dicAlarmLevel}
        getAttrData={(deviceId) => getAttrList(deviceId)}
      />:null}
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          typelist={dicAlarmType}
          levellist={dicAlarmLevel}
        />
      ) : null}
    </>
  );
};

export default AlarmRules;